import json

import aiosqlite
import httpx
from fastapi import HTTPException

city_code = {
    "北京" : "110000",
    "武汉" : "420100"
}

async def weather_search(city: str):
    """
    此代码用于查询指定城市的天气情况

    参数：
    city(str): 城市名称

    返回：
    返回指定城市的天气情况

    """
    code = city_code.get(city)

    api_key = "34b2b3908e9f8e394afe54b0a8271c04"
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?key={api_key}&city={code}&extensions=base"
    async with httpx.AsyncClient() as client:
        responses = await client.get(url=url)
        if responses.content is not None:
            result = json.loads(responses.content)
            lives = result.get("lives")
            live = lives[0]
            return f"目前{live.get('city')}的天气情况是：{live.get('weather')}，温度是：{live.get('temperature')}"
        else:
            return "天气查询工具执行失败。"




async def database_tool(sql: str):
    """
    执行传入的 SELECT SQL 查询，并返回结果（仅支持 SELECT 查询语句）。

    参数:
        sql (str): 需要执行的 SQL 查询语句，必须以 "SELECT" 开头（不区分大小写）

    返回:
        dict:
            {
                "success": True,
                "data": List[Dict[str, Any]]  # 每条记录是一个字段字典
            }

    异常:
        HTTPException:
            - 如果 SQL 不是 SELECT 类型
            - 如果数据库执行失败
    """
    current_sql = sql.strip().lower()
    if not current_sql.startswith("select"):
        raise HTTPException(status_code=400, detail="只允许执行 SELECT 语句")

    try:
        async with aiosqlite.connect(r"D:\hbut\fastbase\db\app.db") as db:
            db.row_factory = aiosqlite.Row
            async with db.execute(sql) as cursor:
                rows = await cursor.fetchall()
                results = [dict(row) for row in rows]
        result = {"success": True, "data": results}
        print(results)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))



DB_PATH = r"D:\hbut\fastbase\db\app.db"

async def get_schema_statements():
    """
    查询 SQLite 数据库中所有用户定义表的建表 SQL（模拟 `.schema` 功能）。

    参数:
        无

    返回:
        dict:
            {
                "success": True,
                "schemas": List[Dict[str, str]]
                # 每个元素包含：
                #   - "table": 表名
                #   - "schema": 建表 SQL 语句
            }

    异常:
        HTTPException: 如果查询过程中发生数据库错误
    """
    try:
        async with aiosqlite.connect(DB_PATH) as db:
            db.row_factory = aiosqlite.Row
            async with db.execute("""
                SELECT name, sql FROM sqlite_master
                WHERE type='table' AND name NOT LIKE 'sqlite_%';
            """) as cursor:
                rows = await cursor.fetchall()
                result = [{"table": row["name"], "schema": row["sql"]} for row in rows]
        print(result)
        return {"success": True, "schemas": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def get_tool_statements():
    infos = []

    infos.append({"tool_name":"weather_search","tool_desc":weather_search.__doc__})
    infos.append({"tool_name":"get_schema_statements","tool_desc":get_schema_statements.__doc__})
    infos.append({"tool_name":"database_tool","tool_desc":database_tool.__doc__})
    return infos